<template>
	<view class="content">
		<view class="search">
			<uv-search placeholder="请输入搜索内容" v-model="keyword" @search="search" @custom="search"></uv-search>
		</view>
		<view class="collect">
			<view class="tab">
				<text class="" @click="CollectList()">
					收藏
				</text>

				<image @click="GoHistory" src="@/static/history.png" mode=""></image>
				<text @click="GoHistory">历史点取</text>
			</view>
		</view>

		<scroll-view class="scroll-view">
			<uv-loading-icon text="加载中" textSize="30rpx" :show="loading"></uv-loading-icon>

			<uv-vtabs :chain="chain" :list="list" keyName="categoryName" :height="height" hdHeight="200rpx"
				@change="change">
					<uv-vtabs-item>
						<view class="item" v-for="(item_sub,index_sub) in childrenList" :key="index_sub">
							<view class="item-title">
								<image :src="item_sub.productPicture" mode="" :lazy-load="true"></image>
							</view>
							<view class="item-content">
								<view class="uv-icon" @click="Collect(item_sub,index_sub)">
									<block v-if="item_sub.collect=='0'">
										<uv-icon name="star" size="24"></uv-icon>
									</block>
									<block v-if="item_sub.collect=='1'">
										<uv-icon name="star-fill" size="24" color="#4f76e4"></uv-icon>
									</block>
								</view>
								<view class="name">
									{{item_sub.commodityName}}/{{item_sub.unit}}
								</view>
								<view class="uv-number-box">
									<uv-number-box @change="ChangeNumber" :name="item_sub.commodityId"
										v-model="item_sub.number" :showMinus="item_sub.number!==0" :min="0">
										<template v-slot:minus>
											<view class="minus">
												<uv-icon name="minus" size="12">
												</uv-icon>
											</view>
										</template>
										<template v-slot:input>
											<input class="input" style="width: 50px;text-align: center;" type="number"
												v-model="item_sub.number" @blur="handleBlur(item_sub)" />
										</template>
										<template v-slot:plus>
											<view class="plus">
												<uv-icon name="plus" color="#FFFFFF" size="12">
												</uv-icon>
											</view>
										</template>
									</uv-number-box>
								</view>
							</view>
						</view>
					</uv-vtabs-item>
				<uv-gap bg-color="#fff" height="200"></uv-gap>
			</uv-vtabs>
		</scroll-view>


		<!-- 加入购物车 -->
		<view class="bottom">
			<image class="icon" src="@/static/cart.png" mode=""></image>
			<text>{{total}}件</text>

			<uv-text type="error" text="清空" @click="clean()"></uv-text>

			<view class="button" @click="GoPurchaseInfo()">
				去下单
			</view>
		</view>
	</view>
</template>

<script>
	import PurchaseAPI from '@/api/purchase'
	import CollectAPI from '@/api/collect'
	export default {
		data() {
			return {
				loading: true,
				keyword: '',
				list: [], // 分类
				chain: false,
				value: 0,
				total: 0,
				chooseList: [], // 选中数据
				height: 0
			}
		},
    computed: {
      childrenList() {
        const _list = this.list[this.value]?.children;
        return _list ? _list : [];
      }
    },
		created() {
			this.purchasecategoryList()
		},
		onReady() {
			uni.createSelectorQuery().select('.bottom').boundingClientRect(data => {
				this.height = uni.getSystemInfoSync().windowHeight - uni.upx2px(180) - data.height
			}).exec()
		},
		methods: {
			clean() {
				// 缓存
				this.chooseList = []
				uni.removeStorageSync("chooseList")

				// 选购的商品
				this.list.forEach(item => {
					item.children.forEach(list => {
						list.number = 0
					})
				})
				// 总数
				this.total = 0
			},

			search(e) {
				this.purchasecategoryList()
			},

			// 1. 获取分类列表
			// 2. 添加采购
			purchasecategoryList() {
				this.loading = true
				PurchaseAPI.purchaseTree({
					commodityName: this.keyword
				}).then(res => {
					this.list = res.data

					if (uni.getStorageSync('chooseList').length !== 0) {
						this.chooseList = uni.getStorageSync('chooseList')
						this.list = this.updatePurchaseCommodityList(this.list, this.chooseList)
						this.totalNum(this.chooseList)
					}
					this.loading = false
				})
			},

			// 根据缓存内容查询购物车的数据
			updatePurchaseCommodityList(arrayA, arrayB) {
				// 遍历数组A中的每个类别
				arrayA.forEach(category => {
					// 遍历类别下的每个商品
					category.children.forEach(commodityA => {
						// 在数组B中查找具有相同id的商品
						const commodityB = arrayB.find(item => item.commodityId === commodityA
							.commodityId);
						// 如果找到匹配的商品，则更新数量
						if (commodityB) {
							commodityA.number = commodityB.number;
						}
					});
				});
				return arrayA;
			},
			change(index) {
				console.log('选项改变：', index)
				this.value = index;
			},
			handleBlur(item) {
				let commodityId = item.commodityId // 商品ID
				let val = item.number // 数量
				this.recalculate(commodityId, val)
			},
			// 更改数量
			ChangeNumber(e) {
				let commodityId = e.name // 商品ID
				let val = e.value // 数量
				this.recalculate(commodityId, val)
			},
			recalculate(commodityId, val) {
				let chooseList = this.chooseList

				// 查询并修改数量
				let obj = this.ChangeNumberList(commodityId)
				if (chooseList.length === 0) {
					obj.number = val
					chooseList.push(obj)
				}
				let index = chooseList.findIndex(item => item.commodityId === obj.commodityId);
				// 如果找到，则进行覆盖
				if (index !== -1) {
					chooseList[index] = obj;
					// 当数量减少为 0  时 移除改数组
					if (val === 0) {
						chooseList.splice(index, 1);
					}
				} else {
					if (val !== 0) {
						obj.number = val
						chooseList.push(obj)
					}
				}
				uni.setStorageSync('chooseList', chooseList)
				setTimeout(() => {
					this.totalNum(chooseList)
				}, 100);
			},
			// 修改数量
			totalNum(list) {
				this.total = list.reduce((acc, item) => acc + Number(item.number), 0);
			},

			// 商品ID
			ChangeNumberList(commodityId) {
				let obj = {}
				this.list.forEach(item => {
					item.children.forEach(item_sub => {
						if (item_sub.commodityId === commodityId) {
							obj = item_sub
						}
					})
				})
				return obj
			},

			Collect(item_sub, index_sub) {
				let collect = item_sub.collect
				let commodityId = item_sub.commodityId
				if (collect == '0') {
          item_sub.collect = '1'
					CollectAPI.collectSave({
						commodityId: commodityId
					})
				} else {
          item_sub.collect = '0'
					CollectAPI.collectSave({
						commodityId: commodityId
					})
				}
			},

			GoHistory() {
				uni.navigateTo({
					url: '/subpackage/commodity/commodity'
				})
			},
			GoPurchaseInfo() {
				// 获取 chooseList 是否为空 空 则提醒 请先添加商品
				if (this.chooseList.length === 0) {
					uni.showToast({
						title: '请先添加商品',
						icon: 'none'
					})
					return
				}
				uni.setStorageSync('chooseList', this.chooseList)
				uni.navigateTo({
					url: '/subpackage/purchase/detail'
				})
			},
			CollectList() {
				uni.setStorageSync('chooseList', this.chooseList)
				uni.navigateTo({
					url: '/subpackage/purchase/collect'
				})
			}
		}
	}
</script>
<style scoped lang="scss">
	.search {
		width: 686rpx;
		display: flex;
		margin-left: 32rpx;
		margin-top: 20rpx;
		align-items: center;
		justify-content: center;
		height: 80rpx;
	}

	.collect {
		height: 100rpx;
		background: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
	}

	.tab {
		width: 686rpx;
		display: flex;
		align-items: center;

		>image {
			margin-left: auto;
			margin-right: 20rpx;
			width: 38rpx;
			height: 38rpx;
		}

		>text {
			font-weight: 600;
			font-size: 28rpx;
			color: #16141D;
		}
	}

	.bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 160rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		z-index: 999;

		.icon {
			margin: 0 20rpx 0 32rpx;
			width: 48rpx;
			height: 48rpx;
		}

		>text {
			font-weight: bold;
			font-size: 28rpx;
			color: #16141D;
			margin-right: 20rpx;

		}

		.button {
			margin-left: auto;
			margin-right: 20rpx;
			width: 431rpx;
			height: 92rpx;
      background: $custom-btn-color;
			box-shadow: 0rpx 5rpx 13rpx 1rpx rgba(67, 119, 236, 0.44);
			border-radius: 46rpx;
			line-height: 92rpx;
			text-align: center;
			font-weight: 600;
			font-size: 32rpx;
			color: #FFFFFF;
		}
	}

	.header {
		padding: 30rpx;
		font-size: 30rpx;
		color: #333;
	}

	.item {
		padding: 10rpx 20rpx;
		display: flex;
		align-items: center;

		&-title {
			>image {
				width: 180rpx;
				height: 140rpx;
				background: #FFFFFF;
				border-radius: 10rpx;
				border: 1rpx solid #707070;
			}

			.text {
				font-weight: 700;
				font-size: 32rpx;
				color: #111;
			}
		}

		&-content {
			margin-left: 20rpx;
			display: flex;
			flex-direction: column;
			width: 300rpx;
			height: 120rpx;
			position: relative;

			.uv-icon {
				position: absolute;
				top: 0;
				right: 0;
			}

			.name {
				font-weight: 600;
				font-size: 28rpx;
				color: #16141D;
			}

			.uv-number-box {
				margin-top: auto;
				margin-left: auto;
			}
		}
	}

	.gap {
		padding: 0 30rpx;
	}

	.minus {
		width: 22px;
		height: 22px;
		border-width: 1px;
		border-color: #E6E6E6;
		border-style: solid;
		border-top-left-radius: 100px;
		border-top-right-radius: 100px;
		border-bottom-left-radius: 100px;
		border-bottom-right-radius: 100px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}

	.input {
		padding: 0 10px;
	}

	.plus {
		width: 22px;
		height: 22px;
		background-color: #16141D;
		border-radius: 50%;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}
</style>